package megrez.keycloak.providers.mqtt;

import java.util.Map;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.keycloak.Config.Scope;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * mqtt client实现
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Slf4j
public class ClientMqttProviderFactory implements MqttProviderFactory {
    private MqttConfigProperties properties;
    private ClientMqttService singleton;

    @Override
    public Map<String, String> getOperationalInfo() {
        return properties.toMap();
    }

    @Override
    public MqttService create(KeycloakSession session) {
        return singleton;
    }

    @Override
    public void init(Scope config) {
        properties = MqttConfigProperties.create(config);
        singleton = new ClientMqttService();
        singleton.initClient(properties);
    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {
        // 不需要实现
    }

    @Override
    public void close() {
        log.info("MQTT Client is closing...");
        if (singleton != null) {
            try {
                singleton.disconnect();
                singleton.close();
            } catch (MqttException e) {
                log.error("MQTT Client close exception", e);
            }
        }
    }

    @Override
    public String getId() {
        return "client";
    }

}
